package com.ai.bitcoin.controller;

import com.ai.bitcoin.annotation.Privilege;
import com.ai.bitcoin.bo.PayRequest;
import com.ai.bitcoin.constant.CodeConstant;
import com.ai.bitcoin.controller.helper.PayControllerHelper;
import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.input.GeneralRequest;
import com.ai.bitcoin.input.RequestHepler;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.output.GeneralReponse;
import com.ai.bitcoin.service.PayService;
import com.ai.bitcoin.service.helper.PayServiceHelper;
import com.ai.bitcoin.service.helper.WeiXinPayServiceHelper;
import com.ai.bitcoin.util.IpUtil;
import com.ai.bitcoin.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequestMapping("/pay")
@Slf4j
@RestController
public class PayController extends CommonController{

    @Value("${asyncTimeout}")
    long asyncTimeout;

    @Autowired
    private PayService payService;

    @Autowired
    private PayServiceHelper payServiceHelper;

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handleException(HttpServletRequest request,
                                                  HttpServletResponse response, RuntimeException e) {
        log.info("", e);
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("SERVICE_UNAVAILABLE");
    }

    @Privilege
    @RequestMapping(value="/isPay", method=RequestMethod.GET, produces = {"application/json;charset=UTF-8" })
    public DeferredResult<String> isPay(HttpServletRequest request,@RequestParam("orderCode") String orderCode) {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        BccUser user = generalRequest.getUser();
        String ip = IpUtil.getClientIp(request);
        if (log.isDebugEnabled()) {
            log.debug("is pay circle ip-->{}",ip);
        }
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        payService.isPay(orderCode,user.getSymbol(),deferredResult);
        return deferredResult;
    }

    @Privilege  //symbol为套餐的symbol  payType = 1 微信支付 tradeType :NATIVE 扫码支付 JSAPI  公众号支付
    @RequestMapping(value="/prepay", method=RequestMethod.GET, produces = {"application/json;charset=UTF-8" })
    public String prePay(HttpServletRequest request,@RequestParam("symbol") String symbol,@RequestParam("payType") Integer payType,@RequestParam("tradeType") String tradeType) throws BusinessException {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        BccUser user = generalRequest.getUser();
        PayRequest payRequest = PayControllerHelper.buildPayRequestData(symbol,payType,tradeType,user,request);
        GeneralReponse generalReponse = payService.prePay(payRequest);
        return JacksonUtils.toJson(generalReponse);
    }

    @RequestMapping(value="/{source}/notify",method={RequestMethod.GET,RequestMethod.POST},produces = {"application/xml;charset=UTF-8" })
    public String callbackPay(@PathVariable("source") String source,HttpServletRequest request) throws IOException {
        if (StringUtils.equals(PayRequest.PayType.WEI_XIN_PAY.toString(),source)) {
            WeiXinPayServiceHelper.WeixinCallBackResult weixinCallBackResult  = payServiceHelper.getWeixinCallbackResponseData(request);
            String response = payService.callBackWeiXinPay(weixinCallBackResult);
            return response;
        } else {
            log.error("invalid source param");
            return JacksonUtils.toJson(new GeneralReponse(CodeConstant.SUCCESS, null, "invalid source param"));
        }
    }

}
